from flask import Flask,request
from todomanager_mysql import TodoManagerWithMysql

# 创建一个服务期程序的实例
app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False

manager = TodoManagerWithMysql()
manager.init_db()

@app.route('/')
def index():
    return '<h1>hello,flask</h1>'


# app.add_url_rule('/',view_func=index)

@app.route('/todos',methods=['GET'])
def get_todo_list():
    return {'todos': [x.__dict__ for x in manager.get_list()]}

@app.route('/create',methods=['POST'])
def create_todo():
    print(request.form)
    if 'title' not in request.form:
        return '参数错误，必须提供title参数',400
    todo = manager.create(request.form['title'])
    return todo.__dict__
@app.route('/mark_completed',methods=['GET'])
def mark_completed():
    if 'id' not in request.args:
        return '参数错误，必须提供id参数',400
    todo_id = int(request.args['id'])
    todo = manager.mark_completed(todo_id)
    if todo_id is not None:
        return todo.__dict__
    else:
        return f'todo not found, todo_id={todo_id}', 404
@app.route('/delete_todo',methods=['POST'])
def delete_todo():
    if 'id' not in request.form:
        return '参数错误，必须提供id参数',400
    todo_id = request.form['id']
    todo = manager.delete(todo_id)
    if todo_id is not None:
        return todo.__dict__
    else:
        return f'todo not found, todo_id={todo_id}', 404

if __name__ == '__main__':
    app.run()
